<?php
class UserController extends BaseClass
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $title;
	public $layout = 'main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
						'actions' => array('index', 'add', 'list', 'process', 'view', 'delete', 'edit', 'admin', 'update'),
						'users' => $this->getAdmins(),
				),
			array('deny', // deny other user to perform actions
					'actions' => array('index', 'add', 'list', 'process', 'view', 'delete', 'edit', 'admin', 'update'),
					'users' => array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->title = "My Next Place::View User";
		$model = Users::model()->findByPk($id);
		$this->render('view', array('model'=>$model, 'id'=>$id));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionAdd()
	{
		$this->title = 'My Next Place::Add User';
		$model = new Users;
		$profile = new UserProfiles;
		$role = new Roles;
		$countries = new Countries;
		if(isset($_POST['Users'])) {
			$profile->attributes = $_POST['UserProfiles'];
			$profile->address = $_POST['UserProfiles']['address'];
			$model->attributes = $_POST['Users'];
			$model->password = !empty($model->password)? md5($model->password):'';
			$model->activation_key = substr((md5(rand()*date('Y-m-d'))),rand(1,9), 7);
			$model->status = 1;
			$model->created = $profile->created = date('Y-m-d H:i:s');
			$profile->user_id = 1;
	
			$valid = 1;
			if(!$model->validate()){
				$valid = 0;
			}
			if(!$profile->validate()) {
				$valid = 0;
			}
		
			if(1 == $valid) {
				if ($model->save()) {
					$userId = Yii::app()->db->getLastInsertId();
					$profile->user_id = $userId;
					 
					if ($profile->save()) {
						Yii::app()->user->setFlash('success','User registered successfully!');
						$this->redirect(Yii::app()->getBaseUrl().'/admin/user');
					}
					else {
						$model->delete($userId);
						Yii::app()->user->setFlash('error','User does not registered due to some technical issue!');
					}
				}
				else {
					Yii::app()->user->setFlash('error','User does not registered due to some technical issue!');
				}
			}
		}
		$this->render('add', array(
				'model'=>$model,
				'profile'=>$profile,
				'role'=>$role,
				'countries'=>$countries,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		if($id != 1) {
			$this->title = 'My Next Place::Update User';
			$role = new Roles;
			$countries = new Countries;
			$model=$this->loadModel($id);
			$profile = $model->userProfiles;

	
		if(isset($_POST['Users'])) {
			$prevPassword = $model->password;
			$profile->attributes = $_POST['UserProfiles'];
			$model->attributes = $_POST['Users'];
			
			$model->password = !empty($_POST['Users']['password']) ? md5($_POST['Users']['password']) : $prevPassword;
			
			$model->activation_key = substr((md5(rand()*date('Y-m-d'))),rand(1,9), 7);
			$model->created = $profile->created = date('Y-m-d H:i:s');
	
			$valid = 1;
			if(!$model->validate()){
				$valid = 0;
			}
			if(!$profile->validate()) {
				$valid = 0;
			}
			if(1 == $valid) {
				if ($model->update()) {
					 
					if ($profile->update()) {
						Yii::app()->user->setFlash('success','User Updated successfully!');
						$this->redirect(Yii::app()->getBaseUrl().'/admin/user/view/id/'.$id);
					}
					else {
						$model->delete($userId);
						Yii::app()->user->setFlash('error','User does not Updated due to some technical issue!');
					}
				}
				else {
					Yii::app()->user->setFlash('error','User does not Updated due to some technical issue!');
				}
			}
		}

		$this->render('update',array(
			'model'=>$model,
			'profile' => $profile,
			'role' => $role,
			'countries' => $countries
		));
	   }
	   else {
	   	$this->redirect(Yii::app()->getBaseUrl().'/admin/user');
	   }
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->title = 'My Next Place::Delete User';
		$model = new Users;
		if($model->updateByPk($id, array('status'=>'2'))) return true;
		else return false;
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->title = 'My Next Place::User List';
		$model = new Users();
		$model->unsetAttributes();
		if(isset($_REQUEST['Users'])) {
			$model->attributes=$_REQUEST['Users'];
		}
		$this->render('index',array(
			'model'=>$model,
		));
	}

	/*
	 * This function will be used to process activities such as activate, deactivate and delete in bulk in grid view of user
	*/
	public function actionProcess() {
		$model = new Users;
		if($_POST['pageAction'] == 'activate')
		{
			if($model->updateByPk($_POST['user'], array('status'=>'1'))) {
				Yii::app()->user->setFlash('success','User (s) Successfully Activated');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/user');
			}
			else {
				Yii::app()->user->setFlash('error','User (s) not Activated');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/user');
			}
		}
		if($_POST['pageAction'] == 'deactivate')
		{
			if($model->updateByPk($_POST['user'], array('status'=>'0'))) {
				Yii::app()->user->setFlash('success','User (s) Successfully Deactivated');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/user');
			}
			else {
				Yii::app()->user->setFlash('error','User (s) not Deactivated');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/user');
			}
		}
		if($_POST['pageAction'] == 'delete')
		{
			if($model->updateByPk($_POST['user'], array('status'=>'2'))) {
				Yii::app()->user->setFlash('success','User (s) Successfully Deleted');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/user');
			}
			else {
				Yii::app()->user->setFlash('error','User (s) not Deleted');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/user');
			}
		}
		exit;
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Users::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='users-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
